<template>
  <div class="pb-6 pt-2 rounded-xl">
    <VisitType v-model:model-value="targetType" v-if="enableBusinessOpportunity" />
    <BindCustomerCell
      title="主题"
      v-model:value="subject"
      placeholder="请输入主题名称"
      required
    />
    <BindCustomerCell
      title="客户"
      v-if="targetType === 1"
      v-model:value="salesMateCustomerName"
      :placeholder="enableCustomInput ? '请输入客户名称' : '请输入并选择客户名称'"
      isLink
      required
      :readOnly="true"
      @click="showSelectCustomerView"
    />
    <BindCustomerCell
      title="商机"
      v-if="targetType === 0"
      v-model:value="opportunityName"
      :placeholder="enableCustomInput ? '请输入客户名称' : '请输入并选择客户名称'"
      isLink
      required
      :readOnly="true"
      @click="showSelectBusinessOpportunityView"
    />
    <BindCustomerCell
      v-model:value="stageName"
      title="沟通环节"
      placeholder="选择沟通环节"
      isLink
      required
      :readOnly="true"
      iconsUrl="https://meetcdn.yxt.com/test-flutter-web/img/tag.svg"
      @click="showTagActionSheet = true"
    />

    <div class="bottom-view mt-4">
      <van-button
        color="#436BFF"
        type="primary"
        block
        :loading="loading"
        @click="onConfirm"
        >确认</van-button
      >
    </div>

    <van-action-sheet
      v-model:show="showTagActionSheet"
      :actions="actions"
      cancel-text="取消"
      @select="onSelectTag"
    />

    <SelectCustomerView ref="selectCustomerRef" @onConfirm="onConfirmCustomer" />
    <SelectBusinessOpportunityView
      ref="selectBusinessOpportunityRef"
      @onConfirm="onConfirmBusinessOpportunity"
    />
  </div>
</template>

<script>
import { mapActions, mapState } from "pinia";
import {
  searchCompanyAPI,
  searchInnerCompanyAPI,
  bindCustomersAPI,
} from "@/services/minutes/customer";
import { useMinutesStore, useCommonStore, useOrderVisitStore } from "@/store";
import { showToast } from "vant";
import BindCustomerCell from "@/views/orderVisit/components/customCell.vue";

import SelectCustomerView from "@/views/minutes/components/customerView/SelectCustomerView.vue";
import VisitType from "@/views/orderVisit/components/visitType.vue";
import SelectBusinessOpportunityView from "@/components/businessOpportunityView/SelectBusinessOpportunityView.vue";

export default {
  name: "bindCustomer",
  components: {
    BindCustomerCell,
    SelectCustomerView,
    VisitType,
  },

  emits: ["onHide"],
  mounted() {
    this.init();

    this.subject = this.recordInfo.subject || "";
  },
  data() {
    return {
      tempSalesMateCustomerName: "",
      salesMateCustomerName: "",
      customerId: "",
      opportunityId: "",
      opportunityName: "",
      targetType: 0,
      stageName: "",
      stageId: "",
      showTagActionSheet: false,
      subject: "",
      customerTopics: [],
      opportunityStages: [],
      loading: false,
    };
  },
  methods: {
    ...mapActions(useOrderVisitStore, {
      getStagesAction: "getStagesAction",
    }),

    ...mapActions(useMinutesStore, {
      fetchAllData: "fetchAllData",
    }),

    ...mapActions(useCommonStore, {
      getFuncPointsAction: "getFuncpPointsAction",
    }),

    showSelectCustomerView() {
      this.$refs.selectCustomerRef.show();
    },

    showSelectBusinessOpportunityView() {
      this.$refs.selectBusinessOpportunityRef.show();
    },

    onConfirmCustomer(v) {
      this.salesMateCustomerName = v.name;
      this.customerId = v.customerId;
    },

    async init() {
      if (this.funcPoints.length === 0) {
        await this.getFuncPointsAction();
      }
      if (this.enableBusinessOpportunity) {
        this.targetType = 0;
      } else {
        this.targetType = 1;
      }
      console.log("init: ", this.enableBusinessOpportunity, this.targetType);
    },

    // 选择商机
    onConfirmBusinessOpportunity(v) {
      this.opportunityId = v.id;
      this.opportunityName = v.name;
      this.customerId = v.customerId;
      this.updateCustomerCommunicationStages(v.id);
    },

    async updateCustomerCommunicationStages(opportunityId) {
      this.opportunityStages = await this.getStagesAction({
        type: 2,
        targetId: opportunityId,
      });
    },

    onSelectTag(v) {
      console.log("onSelectTag: ", v);
      this.stageName = v.name;
      this.stageId = v.id;
      this.showTagActionSheet = false;
    },

    onSelectSuggestions(v) {
      this.salesMateCustomerName = v.value;
    },

    async onConfirm() {
      if (this.targetType === 1) {
        if (!this.customerId || this.salesMateCustomerName.length === 0) {
          showToast("请选择客户名称");
          return;
        }
      } else {
        if (!this.opportunityId || this.opportunityName.length === 0) {
          showToast("请选择商机名称");
          return;
        }
      }
      if (this.stageName.length === 0) {
        showToast("请选择沟通环节");
        return;
      }

      let params = {
        conferenceIds: [this.confId || ""],
        stageId: this.stageId,
        subject: this.subject,
        customerId: this.customerId,
      };

      if (this.targetType === 0) {
        params.opportunityId = this.opportunityId;
      }
      this.loading = true;
      const res = await bindCustomersAPI(params);
      console.log("onConfirm: ", params);
      this.loading = false;
      this.fetchAllData(this.confId);
      this.$emit("onHide");
    },
  },

  computed: {
    ...mapState(useMinutesStore, {
      confId: "conferenceId",
      recordInfo: "recordInfo",
    }),

    ...mapState(useCommonStore, {
      enterNameControl: "enterNameControl",
      funcPoints: "funcPoints",
      enableBusinessOpportunity: "enableBusinessOpportunity",
    }),

    ...mapState(useOrderVisitStore, {
      customerCommunicationStages: "customerCommunicationStages",
    }),

    cp_salesMateCustomerName: {
      get() {
        return this.salesMateCustomerName;
      },
      set(v) {
        this.salesMateCustomerName = v;
      },
    },

    enableCustomInput() {
      return this.enterNameControl;
    },

    actions() {
      if (this.targetType === 1) {
        return this.customerCommunicationStages.map((v) => {
          return {
            name: v.name,
            id: v.id,
          };
        });
      }
      return this.opportunityStages.map((v) => {
        return {
          name: v.name,
          id: v.id,
        };
      });
    },
  },

  watch: {
    tempSalesMateCustomerName(newVal) {
      if (newVal !== this.salesMateCustomerName) {
        this.salesMateCustomerName = "";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.bottom-view {
  margin: 20px 10px;
}
</style>
